package com.springcloud.demo.dynamicTable.dynamic.utils;

import com.springcloud.demo.dynamicTable.dynamic.entity.TableInfoEntity;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @author zhouyang
 * @Description
 * @date 2018/08/13
 */
public class SqlProducer {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public String save(TableInfoEntity tableInfoEntity, Map<String, Object> values) {
        String result = new String();
        SQL sql = new SQL();
        sql.INSERT_INTO(tableInfoEntity.getTableName());
        List<String> columnameList = tableInfoEntity.getColumnameList();
        for(String column: columnameList) {
            Object o = values.get(column);
            if(null != o){
                String s = o.toString();
                if (values.get(column) != null) {
                    sql.VALUES(String.format("`%s`", column), String.format("'%s'", s));
                }
            }
        }
        result = sql.toString();
        logger.info(result);
        return result;
    }

    public String update(TableInfoEntity tableInfoEntity, Map<String, Object> values, Map<String, Object> params) {
        String result = new String();
        SQL sql = new SQL();
        sql.UPDATE(tableInfoEntity.getTableName());
        List<String> columnameList = tableInfoEntity.getColumnameList();
        for(String column: columnameList) {
            Object o = values.get(column);
            if(null != o){
                String s = o.toString();
                if (values.get(column) != null) {
                    sql.SET(String.format("`%s`= '%s'", column, s));
                }
            }
            Object j = params.get(column);
            if(null != j){
                String s = j.toString();
                sql.WHERE(String.format("`%s` = '%s'", column, s));
            }
        }
        result = sql.toString();
        logger.info(result);
        return result;
    }



}
